package com.neusoft.lohas.modules.ivm.web.delivery;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.neusoft.lohas.common.config.Global;
import com.neusoft.lohas.common.persistence.StatusBean;
import com.neusoft.lohas.common.utils.DateUtils;
import com.neusoft.lohas.common.utils.FloatFormat;
import com.neusoft.lohas.common.utils.IdGen;
import com.neusoft.lohas.common.utils.StringUtils;
import com.neusoft.lohas.common.web.BaseController;
import com.neusoft.lohas.modules.ivm.entity.merchant.DeliveryFee;
import com.neusoft.lohas.modules.ivm.entity.merchant.DeliveryIndent;
import com.neusoft.lohas.modules.ivm.entity.merchant.DeliveryMember;
import com.neusoft.lohas.modules.ivm.entity.order.DeliveryDetail;
import com.neusoft.lohas.modules.ivm.entity.order.DeliveryInfo;
import com.neusoft.lohas.modules.ivm.entity.order.Order;
import com.neusoft.lohas.modules.ivm.entity.order.OrderDetail;
import com.neusoft.lohas.modules.ivm.entity.order.Prompt;
import com.neusoft.lohas.modules.ivm.entity.product.Product;
import com.neusoft.lohas.modules.ivm.entity.product.ProductInventoryDetail;
import com.neusoft.lohas.modules.ivm.entity.product.ProductOutDetail;
import com.neusoft.lohas.modules.ivm.entity.workflow.WorkFlow;
import com.neusoft.lohas.modules.ivm.entity.workflow.WorkFlowDetail;
import com.neusoft.lohas.modules.ivm.service.merchant.DeliveryFeeService;
import com.neusoft.lohas.modules.ivm.service.merchant.DeliveryIndentService;
import com.neusoft.lohas.modules.ivm.service.order.DeliveryDetailService;
import com.neusoft.lohas.modules.ivm.service.order.DeliveryInfoService;
import com.neusoft.lohas.modules.ivm.service.order.OrderService;
import com.neusoft.lohas.modules.ivm.service.order.PromptService;
import com.neusoft.lohas.modules.ivm.service.product.ProductOutDetailService;
import com.neusoft.lohas.modules.ivm.service.product.ProductService;
import com.neusoft.lohas.modules.ivm.service.workflow.WorkFlowDetailService;
import com.neusoft.lohas.modules.ivm.service.workflow.WorkFlowService;

/**
 * 订单派送Controller
 * @author jackie.liu
 * @version 2014-12-31
 *
 */
@Controller
@RequestMapping(value = "${adminPath}/ivm/order/delivery")
public class DeliveryController extends BaseController{

	@Autowired
	private OrderService orderService;
	@Autowired
	private DeliveryIndentService indentService;
	@Autowired
	private WorkFlowService workFlowService;
	@Autowired
	private WorkFlowDetailService workFlowDetailService;
	@Autowired
	private DeliveryDetailService deliveryDetailService;
	@Autowired
	private DeliveryInfoService deliveryInfoService;
	@Autowired
	private ProductService productService;
	@Autowired
	private ProductOutDetailService productOutDetailService;
	@Autowired
	private PromptService promptService;
	@Autowired
	private DeliveryFeeService deliveryFeeService;
	
	/**
	 * 生成送货单
	 * @param order
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("ivm:order:view")
	@RequestMapping(value = "deliveryInfo")
	public String deliveryWorkFlow(Order order,
			@RequestParam(value="type", required=false, defaultValue="-1") int type,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		order = orderService.get(order.getId());
		//第一次打开派送详情时，将订单明细表记录copy到送货单明细表，
		//如果是一键还原，也进行初始化，但不做保存
		if (order.getDeliveryInfo()==null || StringUtils.isBlank(order.getDeliveryInfo().getId()) || type == 0) {
			Prompt prompt = promptService.findByMerchantId(order.getMerchant().getId());
			//保存派送单信息deliveryInfo
			DeliveryInfo deliveryInfo = new DeliveryInfo();
			if(type != 0){
				deliveryInfo.setId(IdGen.uuid());
			}else{
				deliveryInfo = order.getDeliveryInfo();
				deliveryInfo.setSpecialMark("");
			}
			deliveryInfo.setOrder(new Order(order.getId()));
			if (prompt!=null && StringUtils.isNotBlank(prompt.getId())) {
				deliveryInfo.setPrompt(prompt.getPrompt());
			}
			deliveryInfo.setName(order.getUserAddress().getName());
			deliveryInfo.setPhone(order.getUserAddress().getPhone());
			if(order.getTimeSlot()!=null){
				deliveryInfo.setStartTime(order.getTimeSlot().getStartTime());
				deliveryInfo.setEndTime(order.getTimeSlot().getEndTime());
				deliveryInfo.setTimeText(order.getTimeSlot().getTimeText());
			}
			deliveryInfo.setAmount(order.getAmount());
			deliveryInfo.setDeliveryNo(createUniqeAuthCode(order.getOrderNo()));//生成送货单号
			deliveryInfo.setAddress(order.getUserAddress().getDetailAddress());
			if(type != 0){
				deliveryInfoService.save(deliveryInfo);
			}
			order.setDeliveryInfo(deliveryInfo);
			//保存派送单清单deliveryDetail
			List<DeliveryDetail> details = getOrderList(order);
			if(type != 0){
				deliveryDetailService.save(details);
				model.addAttribute("toCreate", true);
			}else{
				model.addAttribute("toCreate", false);
			}
			order.setDeliveryList(details);
		}else {
			model.addAttribute("toCreate", false);
		}
		WorkFlow workflow = order.getWorkFlow();
		if(type == 0){//一键还原送货单（只还原，不保存）
			List<DeliveryDetail> details = getOrderList(order);;
			order.setDeliveryList(details);
			DeliveryInfo deliveryInfo = order.getDeliveryInfo();
			deliveryInfo.setAmount(order.getAmount());
			deliveryInfo.setRefund(0);
			model.addAttribute("message", "一键还原送货单成功，保存后生效");
		}
		//获取派送费信息
		DeliveryFee deliveryFee = deliveryFeeService.findByMerchantId(merchant.getId());
		if(StringUtils.isBlank(deliveryFee.getOpenState()) || deliveryFee.getOpenState().equals("0")){
			model.addAttribute("fee", 0);
			model.addAttribute("lowFee", 0);
		}else{
			if(order.getCreateDate().getTime()>=deliveryFee.getBeginDate().getTime() && order.getCreateDate().getTime()<=deliveryFee.getEndDate().getTime()){
        		model.addAttribute("fee", deliveryFee.getAmount());
        		model.addAttribute("lowFee", deliveryFee.getLowFee());
        	}else{
        		model.addAttribute("fee", 0);
            	model.addAttribute("lowFee", 0);
        	}
		}
		model.addAttribute("order", order); //订单信息
		model.addAttribute("workflow", workflow); //流程信息
		model.addAttribute("deliveryInfo", order.getDeliveryInfo()); //送货信息
		model.addAttribute("type", type);
		return "modules/ivm/order/delivery/deliveryDetail";
	}
	
	/**
	 * 设定送货员
	 * @param orderId   订单ID
	 * @param memberId    送货员ID
	 * @param status   提交状态： 0提交，1提交并启动
	 * @param deliveryId    订单送货员关系表ID
	 * @return
	 */
	@RequestMapping(value = "setDeliveryPerson")
	public @ResponseBody Object setDeliveryMan(String orderId, String memberId, String status, String deliveryId){
		Order order = new Order(orderId);
		//创建delivery_indent记录
		DeliveryIndent deliveryIndent = new DeliveryIndent();
		if(StringUtils.isNotBlank(deliveryId)){
			deliveryIndent = indentService.get(deliveryId);
		}
		deliveryIndent.setMerchant(super.merchant);
		deliveryIndent.setOrder(order);
		deliveryIndent.setDeliveryMember(new DeliveryMember(memberId));
		indentService.save(deliveryIndent);
		deliveryIndent = indentService.findByOrderId(orderId);
		//创建流程记录
		WorkFlow workFlow = new WorkFlow();
		workFlow.setStatus(status);
		workFlow.setType("1");
		workFlow.setOrder(order);
		workFlowService.save(workFlow);
		workFlow = workFlowService.findByOrderId(orderId);
		if(status.equals("1")){//向流程明细表插入一条记录
			WorkFlowDetail workFlowDetail = new WorkFlowDetail();
			workFlowDetail.setFlowNode(status);
			workFlowDetail.setWorkFlow(new WorkFlow(workFlow.getId()));
			workFlowDetail.setDeliveryIndent(new DeliveryIndent(deliveryIndent.getId()));
			workFlowDetail.setRemarks("开启派送流程.");
			workFlowDetailService.save(workFlowDetail);
		}
		return getStatusBean(200, "操作成功");
	}
	
	/**
	 * 操作流程
	 * @param orderId    订单ID
	 * @param workFlowId   流程主表ID
	 * @param indentId    送货员订单关系表ID
	 * @param status    状态
	 * @param remarks    备注信息
	 * @return
	 */
	@RequestMapping(value="startWorkFlow")
	public @ResponseBody Object startWorkFlow(
			String orderId, 
			String workFlowId, 
			String indentId, 
			String status, 
			String remarks, 
			String deliveryInfoId, 
			String receiptMarks, 
			String signTime){
		if(status.equals("0")){ //开启派送流程
			int flag = workFlowService.updateStatusById(workFlowId, "1");  //更新流程状态
			if(flag == 0){
				return getStatusBean(400, "操作失败");
			}
		}
		//向流程明细表插入记录
		WorkFlowDetail workFlowDetail = new WorkFlowDetail();
		workFlowDetail.setFlowNode(status);
		workFlowDetail.setWorkFlow(new WorkFlow(workFlowId));
		workFlowDetail.setDeliveryIndent(new DeliveryIndent(indentId));
		workFlowDetail.setRemarks(remarks);
		workFlowDetailService.save(workFlowDetail);
		int flag = orderService.updateOrderTypeById(orderId,status); //更新订单状态和付款状态
		if(flag == 0){
			return getStatusBean(400, "操作失败");
		}
		if(status.equals("2")){   //完成订单派送          更新送货信息表         更新ivm_delivery_indent表的 delivery_date(送货日期)
			DeliveryInfo deliveryInfo = deliveryInfoService.get(deliveryInfoId);
			if(!StringUtils.isNotBlank(signTime)){
				signTime = DateUtils.getDateTime();
			}
			deliveryInfo.setSignTime(DateUtils.parseDate(signTime));
			deliveryInfo.setReceiptMarks(receiptMarks);
			deliveryInfoService.save(deliveryInfo);
			DeliveryIndent deliveryIndent = indentService.get(indentId);
			deliveryIndent.setDeliveryDate(DateUtils.parseDate(signTime));
			indentService.save(deliveryIndent);
			
			//修改版，完成订单后做出库处理
			{  //开始派送订单
				//商品做出库操作
				Order order = orderService.get(orderId);
				List<ProductOutDetail> outDetails = Lists.newArrayList();
				List<Product> products = Lists.newArrayList();
				for (DeliveryDetail deliveryDetail : order.getDeliveryList()) {
					//构建商品信息
					Product product = deliveryDetail.getProduct();
//					if (product.getStock()<=0) {
//						return getStatusBean(400, "商品库存不足，请补货后重试.");
//					}
					List<ProductInventoryDetail> inventoryDetailList = product.getInventoryDetailList();
					//构建出库记录信息
					ProductOutDetail outDetail = new ProductOutDetail();
					outDetail.setMerchant(product.getMerchant());
					outDetail.setProduct(product);
					outDetail.setWeight(deliveryDetail.getNumber()*product.getSpecNum());
					if (inventoryDetailList.size()>0) {
						ProductInventoryDetail inventoryDetail = inventoryDetailList.get(inventoryDetailList.size()-1);
						outDetail.setAmount(FloatFormat.m2_2(outDetail.getWeight()*inventoryDetail.getAmount()/inventoryDetail.getWeight()));
					}else {
						if(product.getStock()<=0){
							outDetail.setAmount(FloatFormat.m2_2(deliveryDetail.getAmount()));
						}else{
							outDetail.setAmount(FloatFormat.m2_2(outDetail.getWeight()*product.getStockAmount()/product.getStock()));
						}
					}
					outDetails.add(outDetail);
					
					//出库，商品库存变更
					product.setStock(product.getStock()-(deliveryDetail.getNumber()*product.getSpecNum()));
					product.setStockAmount(FloatFormat.m2_2(product.getStockAmount()-outDetail.getAmount()));
					products.add(product);
				}
				//开始出库
				productOutDetailService.save(outDetails);
				productService.save(products);
			}
		}
		return getStatusBean(200, "操作成功");
	}
	
	/**
	 * 保存送货单
	 * @param deliveryInfo
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "saveDelivery")
	public String saveDelivery(String[] sorts, String[] detailIds, String[] products, Integer[] numbers, Double[] prices, Double[] amounts, DeliveryInfo deliveryInfo, Model model, RedirectAttributes redirectAttributes) {
		DecimalFormat df = new DecimalFormat("#.00");   
		double amount = 0;
		for(int i=0;i<amounts.length;i++){
			amount += amounts[i];
		}
		amount = Double.valueOf(df.format(amount));
		deliveryInfo.setAmount(amount);
		deliveryInfoService.save(deliveryInfo);  //保存送货单信息
		int len = 0;
		if(numbers != null){
			len = numbers.length;
		}
    	List<DeliveryDetail> deliveryDetails = new ArrayList<DeliveryDetail>();
    	Order order = orderService.get(deliveryInfo.getOrder().getId());
    	//删除送货单商品详情List
    	for(DeliveryDetail deliveryDetail : order.getDeliveryList()){
    		deliveryDetailService.delete(deliveryDetail.getId());
    	}
    	//重新封装送货单商品详情List
    	for (int i = 0; i < len; i++) {
    		DeliveryDetail details = new DeliveryDetail();
    		details.setId(IdGen.uuid());
			details.setMerchant(order.getMerchant());
			details.setOrder(deliveryInfo.getOrder());
			Product product = productService.get(products[i]);
			details.setProduct(product);
			details.setUser(order.getUser());
			details.setNumber(numbers[i]);
			details.setPrice(prices[i]);
    		details.setAmount(amounts[i]);
    		details.setSort(Integer.valueOf(sorts[i]));
    		deliveryDetails.add(details);
    	}
    	//获取派送费信息
		DeliveryFee deliveryFee = deliveryFeeService.findByMerchantId(merchant.getId());
		if(StringUtils.isBlank(deliveryFee.getOpenState()) || deliveryFee.getOpenState().equals("0")){
			model.addAttribute("fee", 0);
			model.addAttribute("lowFee", 0);
		}else{
			if(order.getCreateDate().getTime()>=deliveryFee.getBeginDate().getTime() && order.getCreateDate().getTime()<=deliveryFee.getEndDate().getTime()){
        		model.addAttribute("fee", deliveryFee.getAmount());
        		model.addAttribute("lowFee", deliveryFee.getLowFee());
        	}else{
        		model.addAttribute("fee", 0);
            	model.addAttribute("lowFee", 0);
        	}
		}
    	deliveryDetailService.save(deliveryDetails); //保存送货单详情
    	//model.addAttribute("message", "送货单保存成功");
		model.addAttribute("order", order); //订单信息
		//model.addAttribute("workflow", order.getWorkFlow()); //流程信息
		//model.addAttribute("deliveryInfo", order.getDeliveryInfo()); //送货信息
		model.addAttribute("toCreate", true);
		//return "redirect:"+Global.getAdminPath()+"/ivm/order/delivery/deliveryDetail?id="+order.getId();
		return "modules/ivm/order/delivery/deliveryDetail";
	}
	
	/**
	 * 保存后加载送货单
	 * @param order
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("ivm:order:view")
	@RequestMapping(value = "deliveryDetail")
	public String deliveryDetail(String orderId, HttpServletRequest request, HttpServletResponse response, Model model) {
		Order order = orderService.get(orderId);
		model.addAttribute("toCreate", false);
		model.addAttribute("message", "送货单保存成功");
		WorkFlow workflow = order.getWorkFlow();
		model.addAttribute("order", order); //订单信息
		model.addAttribute("workflow", workflow); //流程信息
		model.addAttribute("deliveryInfo", order.getDeliveryInfo()); //送货信息
		model.addAttribute("type", -1);
		//获取派送费信息
		DeliveryFee deliveryFee = deliveryFeeService.findByMerchantId(merchant.getId());
		if(StringUtils.isBlank(deliveryFee.getOpenState()) || deliveryFee.getOpenState().equals("0")){
			model.addAttribute("fee", 0);
			model.addAttribute("lowFee", 0);
		}else{
			if(order.getCreateDate().getTime()>=deliveryFee.getBeginDate().getTime() && order.getCreateDate().getTime()<=deliveryFee.getEndDate().getTime()){
        		model.addAttribute("fee", deliveryFee.getAmount());
        		model.addAttribute("lowFee", deliveryFee.getLowFee());
        	}else{
        		model.addAttribute("fee", 0);
            	model.addAttribute("lowFee", 0);
        	}
		}
		return "modules/ivm/order/delivery/deliveryDetail";
	}
	
	
	/**
	 * 重置送货单
	 * @param orderId
	 * @return
	 */
	@RequestMapping(value="resetDelivery")
	public @ResponseBody Object resetDelivery(String orderId, int type){
		Order order = orderService.get(orderId);
		/**2015-04-02注释：考虑到送货单中同时包含某个商品的抢购商品和普通商品
		List<DeliveryDetail> deliveryList2 = Lists.newArrayList(); // 订单详情列表（封装不属于原订单商品的List）
		for (DeliveryDetail deliveryDetail : order.getDeliveryList()) {
			boolean flag=false;//标示deliveryDetail是否属于原有订单
			for (OrderDetail orderDetail : order.getDetailList()) {
				if (deliveryDetail.getProduct().getId().equals(orderDetail.getProduct().getId())) {
					flag = true;
					deliveryDetail.setNumber(orderDetail.getNumber());
					deliveryDetail.setPrice(orderDetail.getPrice());
					deliveryDetail.setAmount(orderDetail.getAmount());
					break;
				}
			}
			if(!flag){
				deliveryList2.add(deliveryDetail);
			}
		}
		*/
		List<DeliveryDetail> details = getOrderList(order);
		//type=0:点击一键还原   type=1:确认一键还原  type=2:取消一键还原
		if(type == 1){
			for(DeliveryDetail deliveryDetail : order.getDeliveryList()){
				deliveryDetailService.delete(deliveryDetail.getId());
			}
			deliveryDetailService.save(details);
			return getStatusBean(200, "一键还原送货单成功");
		}else if(type == 2){
			return getStatusBean(300, "取消成功");
		}
		//重置送货单INFO-总金额
		DeliveryInfo deliveryInfo = order.getDeliveryInfo();
		deliveryInfo.setAmount(order.getAmount());
		deliveryInfo.setRefund(0);
		//deliveryInfoService.save(deliveryInfo);
		/*
		deliveryInfo.setName(order.getUserAddress().getName());
		deliveryInfo.setPhone(order.getUserAddress().getPhone());
		deliveryInfo.setStartTime(order.getTimeSlot().getStartTime());
		deliveryInfo.setEndTime(order.getTimeSlot().getEndTime());
		deliveryInfo.setAmount(order.getAmount());
		deliveryInfo.setDeliveryMarks("");
		deliveryInfo.setReceiptMarks("");
		deliveryInfo.setSpecialMark("");
		Prompt prompt = promptService.findByMerchantId(order.getMerchant().getId());
		deliveryInfo.setPrompt(prompt.getPrompt());
		deliveryInfo.setRefund(0);
		//deliveryInfo.setDeliveryNo("");
		if(order.getTimeSlot()!=null){
			deliveryInfo.setStartTime(order.getTimeSlot().getStartTime());
			deliveryInfo.setEndTime(order.getTimeSlot().getEndTime());
			deliveryInfo.setTimeText(order.getTimeSlot().getTimeText());
		}
		deliveryInfo.setAddress(order.getUserAddress().getProvince()+order.getUserAddress().getCity()
				+order.getUserAddress().getCounty()+order.getUserAddress().getAddress());
		deliveryInfoService.save(deliveryInfo);
		//重置订单状态
		order.setOrderType("0");
		orderService.save(order);
		//重置流程
		if(order.getWorkFlow() != null){
			workFlowService.deleteWorkFlowById(order.getWorkFlow().getId());
		}
		//重置派送信息
		DeliveryIndent deliveryIndent = order.getDeliveryIndent();
		if(deliveryIndent != null){
			indentService.deleteIndentById(deliveryIndent.getId());
		}*/
		return getStatusBean(100, "一键还原送货单成功，确认后生效.");
	}
	
	//封装订单商品详情list
	private List<DeliveryDetail> getOrderList(Order order) {
		//订单商品list
		List<DeliveryDetail> details = new ArrayList<DeliveryDetail>();
		int i=0;
		for (OrderDetail detail : order.getDetailList()) {
			DeliveryDetail deliveryDetail = new DeliveryDetail();
			deliveryDetail.setSort(i);
			deliveryDetail.setId(IdGen.uuid());
			deliveryDetail.setMerchant(detail.getMerchant());
			deliveryDetail.setOrder(detail.getOrder());
			deliveryDetail.setProduct(detail.getProduct());
			deliveryDetail.setUser(detail.getUser());
			deliveryDetail.setNumber(detail.getNumber());
			deliveryDetail.setPrice(detail.getPrice());
			deliveryDetail.setAmount(detail.getAmount());
			details.add(deliveryDetail);
			i++;
		}
		return details;
	}

	/**
	 * 预览送货单
	 * @param order
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "previewDelivery")
	public String previewDelivery(Order order,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		order = orderService.get(order.getId());
		model.addAttribute("order", order); //订单信息
		model.addAttribute("deliveryInfo", order.getDeliveryInfo()); //送货单信息
		model.addAttribute("deliveryDetails", order.getDeliveryList()); //送货单明细
		return "modules/ivm/order/delivery/previewDeliveryDetail";
	}
	
	/**
	 * 设置送货员
	 * @param orderIds
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "setDeliveryMember")
	public String setDeliveryMember(String orderIds, HttpServletRequest request, HttpServletResponse response, Model model){
		model.addAttribute("orderIds", orderIds);
		return "modules/ivm/order/delivery/setDeliveryMember";
	}
	
	/**
	 * 保存设置送货员-用于订单列表批量指定送货员
	 * @param orderIds
	 * @param memberId
	 * @return
	 */
	@RequestMapping(value = "setDeliveryMember/save")
	public @ResponseBody Object setDeliveryMemberSave(String orderIds, String memberId, HttpServletRequest request, HttpServletResponse response){
		String[] orderIdItems = orderIds.split(",");
		List<DeliveryIndent> lists = Lists.newArrayList();
		for (String orderId : orderIdItems) {
			Order order = new Order(orderId);
			//创建delivery_indent记录
			DeliveryIndent deliveryIndent = new DeliveryIndent();
			deliveryIndent.setMerchant(super.merchant);
			deliveryIndent.setOrder(order);
			deliveryIndent.setDeliveryMember(new DeliveryMember(memberId));
			lists.add(deliveryIndent);
		}
		indentService.save(lists);
		return getStatusBean(200, "操作成功");
	}
	
	@RequestMapping(value = "checkout")
	public @ResponseBody Object checkout(String orderIds, HttpServletRequest request, HttpServletResponse response){
		String[] orders = orderIds.split(",");
		for (String orderId : orders) {
			Order order = orderService.get(orderId);
			String stauts = "0";
			if (order.getWorkFlow()==null || StringUtils.isBlank(order.getWorkFlow().getId())) {
				stauts="0";
				//创建流程记录
				WorkFlow workFlow = new WorkFlow();
				workFlow.setId(IdGen.uuid());
				workFlow.setStatus("1");
				workFlow.setType("1");
				workFlow.setOrder(order);
				workFlowService.save(workFlow);
				order.setWorkFlow(workFlow);
			}
			if (stauts.equals("0")) {
				int flag = workFlowService.updateStatusById(order.getWorkFlow().getId(), "1");  //更新流程状态
				//初始化流程记录
				WorkFlowDetail workFlowDetail = new WorkFlowDetail();
				workFlowDetail.setFlowNode("0");
				workFlowDetail.setWorkFlow(new WorkFlow(order.getWorkFlow().getId()));
				workFlowDetail.setDeliveryIndent(new DeliveryIndent(order.getDeliveryIndent().getId()));
				workFlowDetail.setRemarks("开启派送流程.");
				workFlowDetailService.save(workFlowDetail);
				stauts="1";
			}
			if (stauts.equals("1")) {
				//签出暂时不做出库，订单完成做出库
//				List<ProductOutDetail> outDetails = Lists.newArrayList();
//				List<Product> products = Lists.newArrayList();
//				for (DeliveryDetail deliveryDetail : order.getDeliveryList()) {
//					//构建商品信息
//					Product product = deliveryDetail.getProduct();
//					List<ProductInventoryDetail> inventoryDetailList = product.getInventoryDetailList();
//					//构建出库记录信息
//					ProductOutDetail outDetail = new ProductOutDetail();
//					outDetail.setMerchant(product.getMerchant());
//					outDetail.setProduct(product);
//					outDetail.setWeight(deliveryDetail.getNumber()*product.getProductUnit().getNumber());
//					if (inventoryDetailList.size()>0) {
//						ProductInventoryDetail inventoryDetail = inventoryDetailList.get(inventoryDetailList.size()-1);
//						outDetail.setAmount(FloatFormat.m2_2(outDetail.getWeight()*inventoryDetail.getAmount()/inventoryDetail.getWeight()));
//					}else {
//						outDetail.setAmount(FloatFormat.m2_2(outDetail.getWeight()*product.getStockAmount()/product.getStock()));
//					}
//					outDetails.add(outDetail);
//					
//					//出库，商品库存变更
//					product.setStock(product.getStock()-(deliveryDetail.getNumber()*product.getProductUnit().getNumber()));
//					product.setStockAmount(FloatFormat.m2_2(product.getStockAmount()-outDetail.getAmount()));
//					products.add(product);
//				}
//				//开始出库
//				productOutDetailService.save(outDetails);
//				productService.save(products);
				//向流程明细表插入记录
				WorkFlowDetail workFlowDetail = new WorkFlowDetail();
				workFlowDetail.setFlowNode(stauts);
				workFlowDetail.setWorkFlow(order.getWorkFlow());
				workFlowDetail.setDeliveryIndent(order.getDeliveryIndent());
				workFlowDetail.setRemarks("开始派送订单.");
				workFlowDetailService.save(workFlowDetail);
				int flag = orderService.updateOrderTypeById(orderId,stauts); //更新订单状态和付款状态
			}
		}
		return getStatusBean(200, "操作成功");
	}
	
	//打开送货员签出确认面板
	@RequestMapping(value = "showCheckoutPanl")
	public String showCheckoutPanl(
			String id,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		Order order = orderService.get(id);
		model.addAttribute("order", order);
		return "modules/ivm/order/checkoutPanl";
	}
	
	//单个订单的送货员签出
	@RequestMapping(value = "orderCheckout")
	public String orderCheckout(Order order, RedirectAttributes redirectAttributes, Model model) {
		String stauts = "0";
		order = orderService.get(order.getId());
		if (order.getWorkFlow()==null || StringUtils.isBlank(order.getWorkFlow().getId())) {
			stauts="0";
			//创建流程记录
			WorkFlow workFlow = new WorkFlow();
			workFlow.setId(IdGen.uuid());
			workFlow.setStatus("1");
			workFlow.setType("1");
			workFlow.setOrder(order);
			workFlowService.save(workFlow);
			order.setWorkFlow(workFlow);
		}
		if (stauts.equals("0")) {
			int flag = workFlowService.updateStatusById(order.getWorkFlow().getId(), "1");  //更新流程状态
			//初始化流程记录
			WorkFlowDetail workFlowDetail = new WorkFlowDetail();
			workFlowDetail.setFlowNode("0");
			workFlowDetail.setWorkFlow(new WorkFlow(order.getWorkFlow().getId()));
			workFlowDetail.setDeliveryIndent(new DeliveryIndent(order.getDeliveryIndent().getId()));
			workFlowDetail.setRemarks("开启派送流程.");
			workFlowDetailService.save(workFlowDetail);
			stauts="1";
		}
		if (stauts.equals("1")) {
			//向流程明细表插入记录
			WorkFlowDetail workFlowDetail = new WorkFlowDetail();
			workFlowDetail.setFlowNode(stauts);
			workFlowDetail.setWorkFlow(order.getWorkFlow());
			workFlowDetail.setDeliveryIndent(order.getDeliveryIndent());
			workFlowDetail.setRemarks("开始派送订单.");
			workFlowDetailService.save(workFlowDetail);
			orderService.updateOrderTypeById(order.getId(),stauts); //更新订单状态和付款状态
		}
		addMessage(redirectAttributes, "送货员签出成功.");
		model.addAttribute("type", "success");
		model.addAttribute("order", order);
		return "modules/ivm/order/checkoutPanl";
	}
	
	//送货单号
	public String createUniqeAuthCode(String orderNo) {
		String authCode = "D"+orderNo.substring(2);
		return authCode;
	}
	
	/**
	 * 根据merchantId和code获取商品信息
	 * @param merchantId
	 * @param code
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "productDetail")
	public @ResponseBody Object productDetail(
			String merchantId,
			String code,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		Product product = productService.getProductByCode(merchantId, String.valueOf(code));
		StatusBean<Product> result = new StatusBean<Product>(product, 200, "成功");
		return result;
	}
}
